var
everyauth = require("everyauth"),
constants = require('../config'),
log4js = require('log4js'),
logger = log4js.getLogger('common.controller.authentication'),
URL = require('url')
;

everyauth.cardgames = require("../everyauth/cardgames");
everyauth.cardgames.everyauth = everyauth;
everyauth.modules.cardgames = everyauth.cardgames;
if (everyauth.cardgames.shouldSetup) {
    everyauth.enabled.cardgames = everyauth.cardgames;
}

module.exports = function (app, info) {
    logger.trace("Init authentication");

    // prevent from timeout error when connecting to platform
    everyauth.everymodule.moduleTimeout(-1);

    everyauth.everymodule.findUserById(function (req, userId, callback) {
        logger.trace('enter findUserById');
        var user = req.session.auth.user;
        if (user) {
            callback(null, user);
        } else {
            callback(["Login error"], null);
        }
    });

    everyauth
	    .cardgames
        .entryPath(info.entryPath)
        .callbackPath(info.callbackPath)
        .step('findOrCreateUser')
        .accepts('res session accessToken extra oauthUser')
        .promises('user')
        .step('sendResponse')
        .accepts('res user')
        .promises(null)
	    .appId(app.platformInfo.client_id)
	    .appSecret(app.platformInfo.client_secret)
        //.myHostname(info.hostName)  // If test on local --> remove this line
	    .handleAuthCallbackError( function (req, res) {
            logger.trace('enter handleAuthCallbackError');
	        res.header('Content-Type', 'text/html');
	        res.write('<script>');
            res.write('window.location="' + constants.MKD_GAMES_PF_URL.AUTH_BASIC + '";');
	        res.end('</script>');
	    })
        .myModuleErrback( function (err, seqValues) {
            logger.trace('enter myModuleErrback');
            var res = seqValues.res;
	        res.header('Content-Type', 'text/html');
	        res.write('<script>');
	        res.write('alert("Login failed.Please try again later.");');
	        res.end('</script>');
        })
	    .findOrCreateUser( function (res, sess, accessToken, extra, cardUser) {
            logger.trace('enter findOrCreateUser');
            var user = {
                profile: cardUser.profile,
                wallet: cardUser.wallet,
                access_token: accessToken,
                refresh_token: extra.refresh_token
            };
	        logger.debug(user);
	        return user;
	    })
	    .addToSession( function (session, user) {
            logger.trace('enter addToSession');
            delete session.auth;
            session.auth = {};
            if (user && user.user) {
		        logger.info("Added to session: " + user.user.profile.device_name);
                session.auth.user = user.user;
            }
            session.auth.loggedIn = !!user.user;
	        session.access_token = user.user.access_token;
	        session.refresh_token = user.user.refresh_token;
	        logger.debug(session);
	    })
	    .sendResponse( function (res, user) {
            logger.trace('enter sendResponse');
	        res.header('Content-Type', 'text/html');
	        res.write('<script>');
	        res.write('window.location="' + info.redirectURL + '";');
	        res.end('</script>');
	    });

    return everyauth;
};
